package org.sippr.controller;

import org.sippr.pojo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
public class FileUploadController {

    @Value("${file.upload.path}")
    private String baseDirectory;

    @PostMapping("/sketch")
    public Result<String> sketch(MultipartFile file) throws IOException {
        String oFile = file.getOriginalFilename();
        if (oFile == null)
            return Result.error("文件为空！");

        String filename = UUID.randomUUID().toString() + oFile.substring(oFile.lastIndexOf("."));
        Path dir = Paths.get(baseDirectory, "\\sketch");
        if (!Files.exists(dir)) {
            Files.createDirectories(dir);
        }

        Path filePath = dir.resolve(filename);
        file.transferTo(new File(filePath.toString()));
        return Result.success(filename);
    }
}
